/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccastestore.servlet;

import it.unitn.science.matr155863_148346_145963.bccastestore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.Asta;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.Product;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.User;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.ProductDetailsValidator;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author berto
 */
public class EditProductSRV extends HttpServlet {

    private DBManager db;
    private static Logger log = Logger.getLogger(EditProductSRV.class);
    private static String destination_dir_path;
    
    @Override
    public void init(ServletConfig config) throws UnavailableException, ServletException{
        super.init(config);
        db=(DBManager)super.getServletContext().getAttribute("db_manager");
    }
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Product product=null;
        String errorOn=null;
        String address="/contents/public/errorPage.jsp";
        
        
        try {
            if(request.getParameter("update")!=null){
                address=update(request,product);
            }else{
                address=addProductToRequest(request,product);
            }
        }catch(Exception ex){ 
            //Error diuring operation
            product=null;
            address="/contents/user/editProduct.jsp";
            errorOn=ex.getMessage();
            request.setAttribute("product", product);
            request.setAttribute("error_on", errorOn);
        } finally {    
                RequestDispatcher dispatcher=request.getRequestDispatcher(address);
                dispatcher.include(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private String update(HttpServletRequest request, Product product) throws Exception {
        String address="/contents/public/errorPage.jsp";
            product=ProductDetailsValidator.createValidateEditProduct(request,db);
            int userId=((User) request.getSession().getAttribute("user")).getId();
            if(product==null){
                    request.setAttribute("error_message", "Unable to edit the product, product doesn't exist.");
            }else if(product.getSellerId()!=userId){
                    request.setAttribute("error_message", "The product isn't yours, you can't endit it.");
            }else{
                try{
                    Integer number_edit=db.editProductDescriptionQuantity(product);
                    if(number_edit==0){
                        throw new Exception("No products updated");
                    }
                    request.setAttribute("mess","The product is edited");
                    List<Asta> aste = db.getAsteAttiveFromProduct(product.getId());
                    
                    request.setAttribute("aste", aste);
                    request.setAttribute("product", product);
                    address="/contents/user/productDetails.jsp";
                    
                }catch(Exception ex){
                    request.setAttribute("error_message", "Unable to edit the product.<br/>"+ex.getMessage());
                    address="/contents/public/errorPage.jsp";
                }
            }
            return address;
    }

    private String addProductToRequest(HttpServletRequest request,Product product) {
        String address="/contents/public/errorPage.jsp";
        if(request.getParameter("id")!=null){
                Integer id=Integer.parseInt(request.getParameter("id"));
                product=db.getProduct(id);
                if(product!=null){
                    request.setAttribute("product", product);
                    address="/contents/user/editProduct.jsp";
                }else{
                    //Product not found
                    request.setAttribute("error_message", "Product not found");
                }
            }else{
                //No product defined
                request.setAttribute("error_message", "No product defined");
            }
        return address;
    }
}
